const jwt = require('jsonwebtoken')
const { updateRoleByID,getAll,addRole,getRoleDetail,delRoleByid,getRoleCount} = require('../db/role')
const { result } =require('../config/result')
const {JWT_SECRET} = require('../config/config.dev')
class RoleConntroller{

  async updateRoleByID(ctx){
    try{

      const ret =  await updateRoleByID(ctx.request.body) 
      if(ret && ret.length>0){
        result.success = true 
        result.message = "更新角色成功"
        result.data = ret
        
      }
      else{
        result.success = false
        result.message = '更新角色不存在'
        result.data = null
      }  
      ctx.body = result
    }catch(e){
        ctx.app.emit('error',e.message,ctx)  
    } 
  }

  async getRoleDetail(ctx){
    try{
      const {id}= ctx.request.params
      const ret =  await getRoleDetail(id) 
      if(ret && ret.length>0){
        result.success = true 
        result.message = "获取角色详情成功"
        result.data = ret
        
      }
      else{
        result.success = false
        result.message = '查询角色不存在'
        result.data = null
      }  
      ctx.body = result
    }catch(e){
        ctx.app.emit('error',e.message,ctx)  
    } 
  }

  async delRoleByID(ctx){
    try{
      const {id}= ctx.request.params
      const ret =  await delRoleByid(id) 
      if(ret && ret.length>0){
        result.success = true 
        result.message = "删除成功"
        result.data = ret
        
      }
      else{
        result.success = false
        result.message = '删除失败'
        result.data = null
      }  
      ctx.body = result
    }catch(e){
        ctx.app.emit('error',e.message,ctx)  
    } 
  }

  async addRole(ctx){
    try{
      const role= ctx.request.body
      const ret =  await addRole(role) 
      if(ret && ret.length>0){
        result.success = true 
        result.message = "添加角色成功"
        result.data = ret
        
      }
      else{
        result.success = false
        result.message = '添加角色失败'
        result.data = null
      }  
      ctx.body = result
    }catch(e){
        ctx.app.emit('error',e.message,ctx)  
    } 
  }

  
  async getRoles(ctx){

    try{
      const retCount =await getRoleCount() 
      const retRows =  await getAll(ctx.request.body)
      if(retCount){
        result.total = retCount[0].total
      }
      if(retRows && retRows.length>0){
        result.success = true
        result.message = "获取角色列表成功"
        result.data = retRows
        ctx.body = result
      }
      else{
        result.data = true
        result.message = '获取角色列表失败'
        result.success = false
        ctx.app.emit('error','获取部门列表失败',ctx)  
        return
      }  
    }catch(e){
        result.data = null
        result.message = e.message
        result.success = false
        ctx.app.emit('error',e.message,ctx)  
    }
      
  }
}

module.exports= new RoleConntroller()